/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.nanosl.norg.general.gui;

import com.nanosl.lib.db.Manager;
import com.nanosl.norg.ent.Relationship;
import com.nanosl.norg.util.NTopComponent;
import java.awt.Color;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import javax.swing.table.DefaultTableModel;
import org.netbeans.api.settings.ConvertAsProperties;
import org.netbeans.spi.actions.AbstractSavable;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.util.Exceptions;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.util.NbBundle.Messages;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(
    dtd = "-//com.nanosl.credit.editor//RelationshipEditor//EN",
autostore = false)
@TopComponent.Description(
    preferredID = "RelationshipEditorTopComponent",
//iconBase="SET/PATH/TO/ICON/HERE", 
persistenceType = TopComponent.PERSISTENCE_ALWAYS)
@TopComponent.Registration(mode = "editor", openAtStartup = false)
@ActionID(category = "Window", id = "com.nanosl.credit.editor.RelationshipEditorTopComponent")
@ActionReference(path = "Menu/Window" /*, position = 333 */)
@TopComponent.OpenActionRegistration(
    displayName = "#CTL_RelationshipEditorAction",
preferredID = "RelationshipEditorTopComponent")
@Messages({
    "CTL_RelationshipEditorAction=RelationshipEditor",
    "CTL_RelationshipEditorTopComponent=RelationshipEditor Window",
    "HINT_RelationshipEditorTopComponent=This is a RelationshipEditor window"
})
public final class RelationshipEditorTopComponent extends NTopComponent implements LookupListener {

    DefaultTableModel relationshipTableModel = new DefaultTableModel();

    public RelationshipEditorTopComponent() {
        initComponents();
        setName(Bundle.CTL_RelationshipEditorTopComponent());
        setToolTipText(Bundle.HINT_RelationshipEditorTopComponent());

        relationshipTableModel = (DefaultTableModel) relationshipTable.getModel();
        resetFields();
    }

    public void resetFields() {
        relationshipTextField.setText("");
    }

    private void fillRelationshipTable() {
        relationshipTableModel.setRowCount(0);
        Collection<Relationship> relationships = manager.find(Relationship.class);
        for (Iterator<Relationship> it = relationships.iterator(); it.hasNext();) {
            Relationship relationship = it.next();
            Object[] row = {relationship};
            relationshipTableModel.addRow(row);
        }
    }

    public static void display() {
        RelationshipEditorTopComponent tc = (RelationshipEditorTopComponent) WindowManager.getDefault().findTopComponent("RelationshipEditorTopComponent");
        tc.open();
        tc.requestActive();
        tc.requestFocus();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        relationshipTextField = new javax.swing.JTextField();
        saveButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        relationshipTable = new javax.swing.JTable();

        jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        org.openide.awt.Mnemonics.setLocalizedText(jLabel2, org.openide.util.NbBundle.getMessage(RelationshipEditorTopComponent.class, "RelationshipEditorTopComponent.jLabel2.text_1")); // NOI18N

        relationshipTextField.setText(org.openide.util.NbBundle.getMessage(RelationshipEditorTopComponent.class, "RelationshipEditorTopComponent.relationshipTextField.text_1")); // NOI18N
        relationshipTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                relationshipTextFieldActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(saveButton, org.openide.util.NbBundle.getMessage(RelationshipEditorTopComponent.class, "RelationshipEditorTopComponent.saveButton.text_1")); // NOI18N
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        relationshipTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Relationship"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        relationshipTable.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                relationshipTableKeyPressed(evt);
            }
        });
        jScrollPane1.setViewportView(relationshipTable);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(relationshipTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(saveButton))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(relationshipTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(saveButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void relationshipTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_relationshipTextFieldActionPerformed
        if (isText(relationshipTextField.getText().trim())) {
            relationshipTextField.setBackground(Color.WHITE);
            try {
                new RelationshipSavable().handleSave();
            } catch (IOException ex) {
                Exceptions.printStackTrace(ex);
            }
        } else {
            errorField(relationshipTextField);
        }
    }//GEN-LAST:event_relationshipTextFieldActionPerformed

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        try {
            new RelationshipSavable().handleSave();
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }
    }//GEN-LAST:event_saveButtonActionPerformed

    private void relationshipTableKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_relationshipTableKeyPressed
        if (evt.getKeyCode() == 127) {
            Relationship relationship = (Relationship) relationshipTable.getValueAt(relationshipTable.getSelectedRow(), 0);
            if (confirm("Are you sure to delete " + relationship + " ?")) {
                manager.delete(Relationship.class, relationship.getRelationship());
                fillRelationshipTable();
            } else {
                showError("Unable to delete " + relationship);
            }
        }
    }//GEN-LAST:event_relationshipTableKeyPressed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable relationshipTable;
    private javax.swing.JTextField relationshipTextField;
    private javax.swing.JButton saveButton;
    // End of variables declaration//GEN-END:variables

    @Override
    public void componentOpened() {
        fillRelationshipTable();
        relationshipTextField.requestFocus();
    }

    @Override
    public void componentClosed() {
        // TODO add custom code on component closing
    }

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    void readProperties(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }

    @Override
    public void resultChanged(LookupEvent le) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    class RelationshipSavable extends AbstractSavable {

        String relationshipName;

        RelationshipSavable() {
            register();
            this.relationshipName = relationshipTextField.getText();
        }

        @Override
        protected String findDisplayName() {
            return relationshipName;
        }

        @Override
        protected void handleSave() throws IOException {

            relationshipName = relationshipTextField.getText().trim();
            if (relationshipName.equals("")) {
                return;
            }
            NotifyDescriptor.Confirmation message = new NotifyDescriptor.Confirmation(
                    "Do you want to save \n " + relationshipName + "?", NotifyDescriptor.OK_CANCEL_OPTION, NotifyDescriptor.QUESTION_MESSAGE);
            Object result = DialogDisplayer.getDefault().notify(message);
//When user clicks "Yes", indicating they really want to save,
//we need to disable the Save action,
//so that it will only be usable when the next change is made.
            if (NotifyDescriptor.YES_OPTION.equals(result)) {


                //Handle the save here...
                Manager manager = Manager.getInstance();
                Relationship relationship = new Relationship(this.relationshipName);
                manager.update(relationship);
                resetFields();
                fillRelationshipTable();
                unregister();
            }

        }

        RelationshipEditorTopComponent tc() {
            return RelationshipEditorTopComponent.this;
        }

        @Override
        public boolean equals(Object obj) {
            if (obj instanceof RelationshipSavable) {
                RelationshipSavable m = (RelationshipSavable) obj;
                return tc() == m.tc();
            }
            return false;
        }

        @Override
        public int hashCode() {
            return tc().hashCode();
        }
    }
}
